<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false" style="padding-bottom: 30px">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="人员名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                  <a-input :disabled="formDisabled" v-model="model.name" placeholder="请输入人员名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gender">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.gender"
                    dictCode="gender"
                    placeholder="请选择性别"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" :hidden="!model.id">
                <a-form-model-item label="人员编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="externalNo">
                  <a-input disabled v-model="model.externalNo" placeholder="请输入人员编号"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-divider>身份证信息</a-divider>
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="身份证号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="idCardNo">
                  <a-input :disabled="formDisabled" v-model="model.idCardNo" placeholder="请输入身份证号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="身份证到期日" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="idCardNoDue">
                  <j-date :disabled="formDisabled" date-format="YYYY-MM-DD" placeholder="请选择身份证到期日" v-model="model.idCardNoDue" style="width: 100%"/>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-divider>学历信息</a-divider>
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="学历" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="highestDegree">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.highestDegree"
                    dictCode="highest_degree"
                    placeholder="请选择学历"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所学专业" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="major">
                  <a-input :disabled="formDisabled" v-model="model.major" placeholder="请输入所学专业"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-divider>劳动关系</a-divider>
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="参保单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="insuredUnit">
                  <select-Company-input :disabled="formDisabled" v-model="model.insuredUnit" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input :query-type="'parent'" :disabled="formDisabled" v-model="model.teamId" :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同有效期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractLife">
                  <j-date :disabled="formDisabled" date-format="YYYY-MM-DD" placeholder="请选择合同有效期" v-model="model.contractLife" style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="关系状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relationshipState">
                  <j-dict-select-tag
                    disabled
                    type="list"
                    v-model="model.relationshipState"
                    dictCode="relationship_state"
                    placeholder="请选择学历"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="劳动合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contract">
                  <j-upload v-if="!waterPdisable" :disabled="formDisabled" v-model="model.contract" :showToast="false" fileFormat=".pdf, .PDF" isSingle></j-upload>
                  <view-upload v-else disabled v-model="model.contract"></view-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="资质证书">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-button @click="handleAddChild" type="primary" style="margin-bottom: 10px" v-if="!formDisabled">新增</a-button>
                <a-table
                  ref="table"
                  bordered
                  size="small"
                  rowKey="key"
                  :components="draggableComponent"
                  :scroll="{x:scrollX}"
                  :columns="childColumns"
                  :dataSource="dataSource"
                  :loading="childLoading"
                  :pagination="false"
                >
                  <template slot="fileSlot" slot-scope="text">
                    <a v-if="waterPdisable" @click="handleNewPre(text)">{{ text }}</a>
                    <span v-if="!text&&!waterPdisable" style="font-size: 12px;font-style: italic;">无文件</span>
                    <a-button v-if="text&&!waterPdisable" icon="download" @click="viewFile(text)">文件列表</a-button>
                  </template>
                  <span slot="action" slot-scope="text, record">
                    <a @click="handleData(record)">编辑</a>
                  </span>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="附件信息">
            <div>
              <div style="color: #f5222d;margin-bottom: 10px;">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</div>
            </div>
            <a-row :gutter="48">
              <a-col :span="6">
                <a-form-model-item label="身份证复印件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="idCard">
                  <j-upload v-if="!waterPdisable" :disabled="formDisabled" v-model="model.idCard" :showToast="false" fileFormat=".pdf, .PDF"></j-upload>
                  <view-upload v-else disabled v-model="model.idCard"></view-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="毕业证复印件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="diploma">
                  <j-upload v-if="!waterPdisable" :disabled="formDisabled" v-model="model.diploma" :showToast="false" fileFormat=".pdf, .PDF"></j-upload>
                  <view-upload v-else disabled v-model="model.diploma"></view-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="学位证复印件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="degree">
                  <j-upload v-if="!waterPdisable" :disabled="formDisabled" v-model="model.degree" :showToast="false" fileFormat=".pdf, .PDF"></j-upload>
                  <view-upload v-else disabled v-model="model.degree"></view-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="6" v-if="!waterPdisable">
                <a-form-model-item label="其他" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="other">
                  <j-upload v-if="!waterPdisable" :disabled="formDisabled" v-model="model.other" :showToast="false" fileFormat=".pdf, .PDF"></j-upload>
                  <view-upload v-else disabled v-model="model.other"></view-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <watermark ref="watermarks" />
      <a-modal
        title="请选择预览或下载"
        :visible="prebtnVisible"
        :footer="null"
        @cancel="handleNewPreCancel"
        :width="240"
      >
        <div style="text-align: center;">
          <a-button shape="circle" icon="search" @click="handlePreviews(prebtnFile)"/>
          <a-divider type="vertical"/>
          <a-button shape="circle" icon="download" @click="handleModals(prebtnFile)"/>
        </div>
      </a-modal>
      <ErpCertificationChildModal ref="childModal" @dataOne="modalOkhandle"></ErpCertificationChildModal>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { mapGetters } from 'vuex'
import moment from 'moment'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import ErpCertificationChildModal from './ErpCertificationChildModal.vue'
import { DragResizable } from '@/mixins/DragResizable'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput';
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import PreviewPdf from '@/utils/previewPdfPublic'
import { axios } from '@/utils/request'
import ViewUpload from '@/views/components/ViewUpload.vue'
import watermark from '@/views/erp/hr/certificatefile/companyQualification/modules/watermark.vue'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'

export default {
  name: 'ErpCertificatePersonnelForm',
  components: {
    SelectUserByDep,
    SelectTeamInput,
    SelectCompanyInput,
    ErpCertificationChildModal,
    ViewUpload,
    watermark,
    ViewFileModal
  },
  mixins:[DragResizable,viewFile],
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    // 是否添加水印
    waterPdisable: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {
        relationshipState:'3'
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
      confirmLoading: false,
      validatorRules: {
        name: [{ required: true, message: '请输入人员名称!', trigger: 'blur' }],
        idCardNo: [
          { required: true, message: '请输入身份证号!' },
          { pattern: '^\\d{6}(18|19|20)?\\d{2}(0[1-9]|1[012])(0[1-9]|[12]\\d|3[01])\\d{3}(\\d|[xX])$', message: '身份证号格式不正确' }
        ],
        gender: [{ required: true, message: '请选择性别!', trigger: ['change', 'blur'] }],
        idCardNoDue: [{ required: true, message: '请选择身份证到期日!', trigger: ['change', 'blur'] }],
        highestDegree: [{ required: true, message: '请选择学历!', trigger: ['change', 'blur'] }],
        major: [{ required: true, message: '请输入所学专业!', trigger: 'blur' }],
        insuredUnit: [{ required: true, message: '请选择参保单位!', trigger: ['change', 'blur'] }],
        teamId: [{ required: true, message: '请选择所属团队!', trigger: ['change', 'blur'] }],
        relationshipState: [{ required: true, message: '请选择关系状态!', trigger: ['change', 'blur'] }],
        contractLife: [{ required: true, message: '请选择合同有效期!', trigger: ['change', 'blur'] }],
        contract: [{ required: true, message: '请选择劳动合同!' }],
      },
      url: {
        add: '/api/erp/files/employee/erpEmployeeExternalFile/add',
        edit: '/api/erp/files/employee/erpEmployeeExternalFile/edit',
        getBillNo: '/api/erp/files/employee/erpEmployeeExternalFile/gainBillNo'
      },
      activeKey: ['1', '2', '3'],
      dataSource: [],
      childLoading: false,
      childColumns: [
        {
          title: '注册类别',
          align: 'center',
          dataIndex: 'categoryId',
          ellipsis: true,
          width:120,
          customRender: (value, record, index) => {
            let text = ''
            if(!value){
              text = ''
            } else {
              text = filterMultiDictText(this.dictOptions['categoryId'], value + '')
            }
            return {
              children: text,
              attrs: { rowSpan: record.childspan },
            };
          },
        },
        {
          title:'注册专业',
          align:"center",
          dataIndex: 'professionalId',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['professionalId'], text + '')
            }
          },
          ellipsis: true,
          width:120,
        },
        {
          title:'证书名称',
          align:"center",
          dataIndex: 'certificateName',
          ellipsis: true,
          width:120,
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['certificateName'], text + '')
            }
          }
        },
        {
          title:'颁发机构',
          align:"center",
          dataIndex: 'issueBody',
          ellipsis: true,
          width:120,
        },
        {
          title:'颁发日期',
          align:"center",
          dataIndex: 'issueDate',
          ellipsis: true,
          width:120,
        },
        {
          title:'继续教育时间',
          align:"center",
          dataIndex: 'educationDate',
          ellipsis: true,
          width:120,
        },
        {
          title:'到期时间',
          align:"center",
          dataIndex: 'endDate',
          ellipsis: true,
          width:120,
          customRender: (text, r) => {
            if (r.isAlways==1) {
              return ''
            } else {
              return text
            }
          },
        },
        {
          title:'附件',
          align:"center",
          dataIndex: 'attachment',
          scopedSlots: { customRender: 'fileSlot' },
          ellipsis: true,
          width:120,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed: 'right',
          width:150,
          scopedSlots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'action' }
        }
      ],
      dictOptions:{},
      prebtnVisible: false,
      prebtnFile: ''
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.initDictConfig()
    this.newInitDictConfig()
    if(this.disabled){
      this.childColumns.pop()
    }
    this.customKey = 'childColumns'
    this.childColumnswidth = this.childColumns.map(val => {
      return val.width
    })
  },
  methods: {
    ...mapGetters(['userInfo']),
    handleNewPre(value){
      this.prebtnVisible = true
      this.prebtnFile = value
    },
    handleNewPreCancel(){
      this.prebtnVisible = false
      this.prebtnFile = ''
    },
    handleModals(value){
      this.$refs.watermarks.visible = true
      this.$refs.watermarks.wValue = value
    },
    handlePreviews(value){
      let fileType = value.substr(-3)
      let text = `${this.userInfo().orgCodeTxt}-${this.userInfo().realname}-${this.userInfo().workNo}`
      let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + value
      axios({
        url: url,
        params: {},
        method:'get' ,
        responseType: 'blob',
      }).then(res=>{
        if(fileType==='pdf'){
          new PreviewPdf({
            blob: res,
            docTitle: fileType,
            isAddWatermark: true, // 是否需要添加水印
            watermark: { // watermark必填 里面可以不填
              type: 'canvas',
              text: text,
            }
          })
        }else{
          // location.href = url
          this.$message.error('非pdf文件不可查看')
        }
        
      })
    },
    async newInitDictConfig() {
        initDictOptions('erp_certificate_name_management,certificate_name,id').then(async(res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'certificateName', res.result)
          }
        })
      },
    async initDictConfig(){
      let res = await getAction('/api/erp/files/professional/erpProfessionalCategory/list', { pageNo: 1,pageSize: -1 })
      if (res.success) {
        let data = res.result.records || res.result
        if(data.length>0){
          this.$set(this.dictOptions, 'categoryId', data.map(v => {
            return {
              text: v.registrationCategory,
              title: v.registrationCategory,
              value: v.id
            }
          }))
          let newObj = []
          data.forEach(val => {
            if(val.children&&val.children.length>0){
              newObj.push(...val.children.map(c => {
                return {
                  text: c.registeredProfessional,
                  title: c.registeredProfessional,
                  value: c.id
                }
              }))
            }
          })
          this.$set(this.dictOptions, 'professionalId', newObj)
        }
      }
    },
    getBillNoData(){
      getAction(this.url.getBillNo).then(res => {
        if(res.success){
          this.$set(this.model, 'externalNo', res.result)
        }
      })
    },
    add() {
      this.edit(this.modelDefault)
      this.model.proposer = this.userInfo().empId //当前登录人
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss') //申请时间
      this.getBillNoData()
    },
    edit(record) {
      this.$refs['form'].clearValidate()
      this.model = Object.assign({}, record)
      if(this.model.id){
        let data = Object.assign([],this.model.certificateList)
        if(data.length){
          let carr = data.reduce((result,item) => {
            const key = item.categoryId
            if(!result[key]){
              result[key] = []
            }
            result[key].push(item)
            return result
          },{})
          let arr = []
          Object.keys(carr).map(zevel => {
            let len = carr[zevel].length
            arr.push(...carr[zevel].map((dItem,index) => {
              return {
                ...dItem,
                childspan: index === 0 ? len : 0
              }
            }))
          })
          this.dataSource = arr.map((item,index) => {
            return {
              ...item,
              key: index
            }
          })
        } else {
          this.dataSource = []
        }
        
      } else {
        this.dataSource = []
      }
      this.visible = true
      this[this.customKey].forEach((val,index) => {
        val.width = this[this.customKey+'width'][index]
      })
    },
    modalOkhandle(data,flag){
      if (flag) {
        this.dataSource.push(data)
      } else {
        this.dataSource.splice(data.key, 1, data);
      }
      let source = this.dataSource
      let carr = source.reduce((result,item) => {
        const key = item.categoryId
        if(!result[key]){
          result[key] = []
        }
        result[key].push(item)
        return result
      },{})
      let arr = []
      Object.keys(carr).map(zevel => {
        let len = carr[zevel].length
        arr.push(...carr[zevel].map((dItem,index) => {
          return {
            ...dItem,
            childspan: index === 0 ? len : 0
          }
        }))
      })
      this.dataSource = arr.map((item,index) => {
        return {
          ...item,
          key: index
        }
      })
    },
    handleData(record) {
      this.$refs.childModal.edit(record)
      this.$refs.childModal.title = '编辑'
      this.$refs.childModal.disableSubmit = false
    },
    handleAddChild(){
      this.$refs.childModal.add()
      this.$refs.childModal.title = '新增'
      this.$refs.childModal.disableSubmit = false
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          that.model.certificateList = that.dataSource
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
                that.$emit('unButtonDisable')
              }
            })
            .catch((error) => {
              that.$emit('unButtonDisable')
            })
            .finally(() => {
              that.confirmLoading = false
            })
        } else {
          that.$emit('unButtonDisable')
        }
      })
    },
  },
}
</script>
